//
//  LKHomeViewModel.swift
//  新浪微博
//
//  Created by 胡不归是大虾 on 16/9/27.
//  Copyright © 2016年 胡不归是大虾. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage
//请求网络数据
class LKHomeViewModel: NSObject {
    //ViewModel数组
    lazy var viewModelArray : [LKStatusViewModel] = [LKStatusViewModel]()
    func requestData (isPullingUp: Bool,finished:@escaping ((Bool,Int)->())) {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        var parameters = ["access_token":LKUserInforViewModel.sharedUserInfoViewModel.userInfoModel?.access_token ?? ""]
        //添加上拉刷新需要的参数maxid
        //需要判断是否处于上拉状态
        if isPullingUp {
            //获取数组最后一个id
            let id = viewModelArray.last?.status?.id ?? 0
            parameters["max_id"] = "\(id - 1)"
        } else
        {
            //下拉刷新请求数据
            let id = viewModelArray.first?.status?.id ?? 0
            parameters["since_id"] = "\(id)"
        }
        LKNetworkTool.sharedTool.request(method: .Get, urlString: urlString, parameters: parameters) { (respondObejct, error) in
            if error != nil {
                print(error)
                SVProgressHUD.showError(withStatus: "请求用户数据失败")
                return
            }
            //用字典接收一下数据
            let dict = respondObejct as! [String : Any]
            //在字典中取值出status的值
            guard let array = dict["statuses"] as? [[String : Any]] else{
                finished(false,0)
                return
            }
            //遍历数组,字典转模型
            var tempArray = [LKStatusViewModel]()
            for item in array{
                let viewModel =  LKStatusViewModel()
                let status = LKStatus()
                status.yy_modelSet(with: item)
                viewModel.status = status
                tempArray.append(viewModel)
//                self.viewModelArray.append(viewModel)
            }
            //拼接数组
            if isPullingUp {
                self.viewModelArray += tempArray
            }
            else{
                self.viewModelArray = tempArray + self.viewModelArray
            }
            //执行成功的回调
//            finished(true,tempArray.count)
            //此处先不要回调,先下载完所有的单张图片再进行回调
            self.cacheSingleImage(dataArray: tempArray, finishedClosure: finished)
        }
    }
    private func cacheSingleImage (dataArray: [LKStatusViewModel],finishedClosure:@escaping (Bool,Int)->()) {
        //遍历数组,找出图片只有一张的微博
        //实例化调度组
        let group = DispatchGroup.init()
        for viewModel in dataArray {
            //如果图片只有一张,
            if viewModel.pic_urls?.count == 1 {
                //就异步下载
                let url = URL(string: viewModel.pic_urls?.first?.wap_pic ?? "")
                //开始异步下载前要入组
                group.enter()
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, _, _, _, _) in
                    //下载完成出组
                    group.leave()
                })
            }
        }
        //调度组完成
        group.notify(queue: DispatchQueue.main) { 
            finishedClosure(true, dataArray.count)
        }
    }
}
